/**
 * 
 */
package com.samulegao.android.pis;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.samulegao.android.pis.ToDos.ToDoColumn;

/**
 * @author zhanfeng.gss
 * 
 */
public class TodoEditor extends Activity {

	private static final String TAG = "TodoEditor";

	private static final int STATE_INSERT = 1;
	private static final int STATE_EDIT = 2;

	private static final String[] PROJECTION = { ToDoColumn._ID,
			ToDoColumn.TITLE, ToDoColumn.DESC, ToDoColumn.CREATED_DATE,
			ToDoColumn.MODIFIED_DATE, ToDoColumn.DEADLINE_TIME };

	private static final int INDEX_TITLE = 1;
	private static final int INDEX_DESC = 2;
	private static final int INDEX_CREATED = 3;
	private static final int INDEX_MODIFIED = 4;
	private static final int INDEX_DEADLINE = 5;

	private int mState;
	private Uri mUri;
	private Cursor mCur;

	EditText titleText;
	EditText descText;
	DatePicker deadlinePicker;
	TextView createdView;
	TextView modifiedView;

	Button btn_ok;
	Button btn_cancel;

	String lblOK;
	String lblCancel;

	Calendar c = Calendar.getInstance();

	private OnClickListener btnOkClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			saveTodos();
			TodoEditor.this.finish();
		}
	};

	private OnClickListener btnCancelClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (mState == STATE_INSERT) {
				delTodo();
				TodoEditor.this.finish();
			} else if (mState == STATE_EDIT) {
				TodoEditor.this.finish();
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.todo_editor);

		final Intent intent = getIntent();

		final String action = intent.getAction();

		final Resources res = getResources();
		if (Intent.ACTION_EDIT.equals(action)) {
			mState = STATE_EDIT;
			mUri = intent.getData();
			lblOK = res.getString(R.string.save_edit);
			lblCancel = res.getString(R.string.cancel_edit);
		} else if (Intent.ACTION_INSERT.equals(action)) {
			mState = STATE_INSERT;
			lblOK = res.getString(R.string.save_edit_new);
			lblCancel = res.getString(R.string.cancel_edit_new);
			String title = intent.getStringExtra(ToDoColumn.TITLE);
			ContentValues values = null;
			if (!TextUtils.isEmpty(title)) {
				values = new ContentValues();
				values.put(ToDoColumn.TITLE, title);
			}
			mUri = getContentResolver().insert(intent.getData(), values);
			if (mUri == null) {
				Log.e(TAG, "Failed to insert new todos into "
						+ getIntent().getData());
				finish();
				return;
			}
		} else {
			Log.e(TAG, "Unknown action, exiting");
			finish();
			return;
		}

		mCur = managedQuery(mUri, PROJECTION, null, null, null);

		titleText = (EditText) findViewById(R.id.title);

		descText = (EditText) findViewById(R.id.desc);

		deadlinePicker = (DatePicker) findViewById(R.id.deadline);

		createdView = (TextView) findViewById(R.id.created);

		modifiedView = (TextView) findViewById(R.id.modified);

		btn_ok = (Button) findViewById(R.id.btn_save);
		btn_cancel = (Button) findViewById(R.id.btn_quit);

		btn_ok.setOnClickListener(btnOkClickListener);
		btn_cancel.setOnClickListener(btnCancelClickListener);

		btn_ok.setText(lblOK);
		btn_cancel.setText(lblCancel);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mCur != null) {
			mCur.moveToFirst();
			String title = mCur.getString(INDEX_TITLE);
			String desc = mCur.getString(INDEX_DESC);
			long created = mCur.getLong(INDEX_CREATED);
			long modified = mCur.getLong(INDEX_MODIFIED);
			long deadline = mCur.getLong(INDEX_DEADLINE);
			titleText.setText(title);
			descText.setText(desc);
			c.setTimeInMillis(deadline);
			deadlinePicker.init(c.get(Calendar.YEAR), c.get(Calendar.MONTH),
					c.get(Calendar.DAY_OF_MONTH), null);
			c.setTimeInMillis(created);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			createdView.setText(sdf.format(c.getTime()));
			c.setTimeInMillis(modified);
			modifiedView.setText(sdf.format(c.getTime()));
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	private void saveTodos() {
		if (mCur != null) {
			ContentValues values = new ContentValues();
			values.put(ToDoColumn.TITLE, titleText.getText().toString());
			values.put(ToDoColumn.DESC, descText.getText().toString());
			c.set(deadlinePicker.getYear(), deadlinePicker.getMonth(),
					deadlinePicker.getDayOfMonth());
			values.put(ToDoColumn.DEADLINE_TIME, c.getTimeInMillis());
			values.put(ToDoColumn.MODIFIED_DATE, System.currentTimeMillis());
			getContentResolver().update(mUri, values, null, null);
		}
	}

	private void delTodo() {
		if (mCur != null) {
			mCur.close();
			mCur = null;
			getContentResolver().delete(mUri, null, null);
		}
	}

	private void exit() {
		finish();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			AlertDialog confirm = new AlertDialog.Builder(this)
					.setTitle(R.string.dialog_title)
					.setMessage(R.string.dialog_msg)
					.setPositiveButton(lblOK,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									saveTodos();
									exit();
								}
							})
					.setNegativeButton(lblCancel,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									if (mState == STATE_INSERT) {
										delTodo();
									}
									exit();
								}
							}).create();
			confirm.show();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
